<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户信息</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 白色区域内容 -->
    <div class="page_content">
      <div class="flex">
        <div class="input_box">
          <el-input v-model="input3" placeholder="按照关键字搜索" class="input-with-select">
            <template #append>
              <el-button @click="searchByPhone"><i class="el-icon-search"></i><el-icon><Search /></el-icon></el-button>
            </template>
          </el-input>
        </div>



        <!-- //添加用户窗口 -->
        <el-dialog title="添加用户信息" v-model="addDialogVisible">
          <el-form :model="addForm" label-position="left" label-width="80px">
            <el-form-item label="id">
              <el-input v-model="addForm.id"></el-input>
            </el-form-item>
            <el-form-item label="用户名">
              <el-input v-model="addForm.username"></el-input>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-input v-model="addForm.sex"></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="是否启用">
              <el-input v-model="addForm.enable"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addUser(addForm)">确 定</el-button>
          </div>
        </el-dialog>

        <div class="flex">
          <!-- 增加一个删除的按钮 -->
        <el-button type="danger" @click="showDeleteCheckbox=!showDeleteCheckbox">{{ showDeleteCheckbox ? '取消删除' : '删除' }}</el-button>
          <el-button type="button" @click="addDialogVisible = true" class="myButton">新建</el-button>
        </div>
      </div>
      <!-- 显示复选框 -->
      <el-table :data="tableData" stripe style="width: 100%"  @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :selectable="showDeleteCheckbox"></el-table-column>
         <el-table-column prop="id" label="id" />
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="mobile" label="电话号码" />
          <el-table-column prop="sex" label="性别" :formatter="formatSex"/>
          <el-table-column prop="password" label="密码" />
          <el-table-column prop="updateTime" label="修改时间" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column label="启用">
          <template #default="{row}">
          <el-switch v-model="row.enable" active-value="1" inactive-value="0" :active-color="isActiveColor" :inactive-color="isInactiveColor" @click="isUse(row)"/>
          </template>
          </el-table-column>

          <!-- <el-table-column prop="enable" label="启用" :formatter="formatIsUse"/> -->
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="{row}">
            <el-button type="button" @click="handleEdit(row)" class="myButton1">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 删除按钮 -->
      <div style="text-align: center; margin-top: 20px;" v-if="showDeleteCheckbox">
        <el-button type="danger" @click="deleteSelectedRows()">删除所选</el-button>
      </div>
    </div>

    <!-- 编辑窗口 -->
    <el-dialog title="编辑用户信息" v-model="editDialogVisible">
      <el-form :model="editForm" label-position="left" label-width="80px">
       <el-form-item label="id">
              <el-input v-model="editForm.id"></el-input>
            </el-form-item>
            <el-form-item label="用户名">
              <el-input v-model="editForm.username"></el-input>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-input v-model="editForm.sex"></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="editForm.password"></el-input>
            </el-form-item>
            <el-form-item label="是否启用">
              <el-input v-model="editForm.enable"></el-input>
            </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelEdit">取 消</el-button>
        <el-button class="myButton1" type="primary" @click="submitEdit">确 定</el-button>
      </div>
    </el-dialog>
    <div class="pagination">
    <el-pagination v-model:current-page="page" v-model:page-size="size" :page-sizes="[5,10,20,30]" :small="small" :disabled="disabled"
      :background="background" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>

  </div>
</template>

<script setup>
import { h, onMounted, reactive, ref } from 'vue';
import axios from '../../utils/axios';
import { ElMessageBox, ElMessage } from 'element-plus';

let tableData = reactive([]);
const input3 = ref('');
//分页设置
let page = 1;
let size = 5;
const small = ref(false)
const disabled = ref(false)
const background = ref(false)
const total = ref(0)

const editDialogVisible = ref(false);
const addDialogVisible = ref(false);
const editForm = reactive({
  id: '',
  username: '',
  mobile: '',
  sex: '',
  password: '',
  updateTime: '',
  createTime: '',
  enable: 0,
});
const addForm = reactive({
   id: '',
  username: '',
  mobile: '',
  sex: '',
  password: '',
  updateTime: '',
  createTime: '',
  enable: 0,
});
const showDeleteCheckbox = ref(false);
let selectedRows = reactive([]);
let seletionIds = reactive([]);

const handleSizeChange = (val) => {
  size = val;
  refreshTableData();
} 
const handleCurrentChange = (val) => {
  page = val;
  refreshTableData();
}

const handleEdit = (row) => {
  // 对editForm进行初始化
  editForm.id = row.id;
  editForm.username = row.username;
  editForm.mobile = row.mobile;
    editForm.sex = row.sex;
  editForm.mobile = row.mobile;
  editForm.password = row.password;
    editForm.updateTime = row.updateTime;
  editForm.createTime = row.createTime;
  editForm.enable = row.enable;
  editDialogVisible.value = true;
};

const cancelEdit = () => {
  editDialogVisible.value = false;
  resetEditForm();
};

const submitEdit = () => {
  axios.put('/user/', editForm).then((res) => {
    console.log('提交修改：', editForm);
    console.log("res为：",res)
    // console.log(res) 
    const updatedRow = res.data;
    const index = tableData.findIndex((item) => item.id === updatedRow.id);
    if (index !== -1) {
      tableData[index] = updatedRow;
    }
    editDialogVisible.value = false;
  }).catch((err) => {
    console.error(err);
    // 使用element-plus的message组件
    ElMessage.error('提交失败，请稍后再试');
  });
};


const formatSex = (row) => {
return row.sex ? '女' : '男';
};

const formatIsUse = (row) => {
return row.isUse ? '否' : '是';
};

const isActiveColor = '#ff4949'
const isInactiveColor =  '#13ce66'



const isUse = (row) => {
  console.log("row.id",row.id)
  console.log("enable", row.enable)
  axios.put('/user/', {id: row.id, enable: row.enable}).then((res) => {
    console.log("res为：",res)
     ElMessage.success('状态更新成功，请稍后再试');
      console.log("tabl0eData")
      console.log(tableData)
      refreshTableData()
  }).catch((error) => {
  console.log(error)
   ElMessage.error('状态更新失败，请稍后再试');
  })
}

const resetEditForm = () => {
  editForm.id = tableData[tableData.length - 1].id + 1;
  editForm.username = '';
  editForm.mobile = '';
  editForm.sex = '';
  editForm.password = '';
  editForm.updateTime = '';
  editForm.createTime = '';
  editForm.enable = 0;
};

const handleSelectionChange = (value) => {
  selectedRows = reactive([]);
  selectedRows.value = value;
  // console.log("要删除value为：")
  // console.log(value)
  // for(let i=0; i<value.length; i++){
  //   seletionIds.push(value[i].id)
  // }
  
  // console.log("selectionIds为：")
  // console.log(seletionIds)
};


//根据手机号模糊查询
const searchByPhone = () => {
  if(!input3.value) {
    axios.get('/user/list').then((res) => {
      console.log("res为：")
      console.log(res)
      if (res.code === 200) {
        const result = res.data;
        for (let i in result) tableData.push(result[i]);
      } else {
        ElMessage.error(res.msg);
      }
    }).catch((err) => {
      console.log(err);
      ElMessage.error('获取用户列表失败');
    });
  } else {
    axios.get(`/user/search/${input3.value}`).then((res) => {
      console.log('提交查询：', input3.value);
    console.log("res为：")
    console.log(res)
    console.log(res.data)
      if (res.code === 200) {
        const result = res.data;
        tableData = result;
        console.log(tableData)
      } else {
        ElMessage.error(res.msg);
      }
    }).catch((err) => {
      console.log(err);
      ElMessage.error('获取用户列表失败');
    });
  }
};



const deleteSelectedRows = () => {
  const ids = selectedRows.value.map((row) => row.id);
  for (let id of ids) {
    axios.delete('/user/' + id).then((res) => {
      console.log("删除后的数据如下");
      console.log(res);
      console.log(res.code);
      if (res.code == 200) {
        showDeleteCheckbox.value = false;
        selectedRows.value = [];
        ElMessage.success('删除成功！');
        refreshTableData();
      } else {
        ElMessage.error('删除失败！');
      }
    }).catch((err) => {
      console.error(err);
      ElMessage.error('删除失败，请稍后再试');
    });
  }
};

//添加用户的方法
const addUser = (addForm) => {
  addDialogVisible.value = true;
  axios.post('/user/',addForm).then((res) => {

    console.log("添加用户res为：")
    console.log(res)
    if (res.code == 200) {
      tableData.push(res.data);
      ElMessage.success("添加用户成功");
    } else {
      ElMessage.error(res.msg);
    }
  }).catch((err) => {
    console.log(err);
    ElMessage.error('添加用户失败');
  });
};

//初始化请求数据
const refreshTableData = () => {
  axios.get(`/user/list/${page}/${size}`).then((res) => {
    console.log("res为：")
    console.log(res)
    if (res.code == 200) {

      tableData.splice(0, tableData.length);
      total.value = res.data.total
      const result = res.data.list;
      for (let i in result){
       // 将数值类型的 0 或者 1 转换为字符串类型的 "0" 或者 "1"
        result[i].enable = String(result[i].enable);
      tableData.push(result[i]);
      }
        console.log("tableData", tableData)
    } else {
      ElMessage.error(res.msg);
    }
  }).catch((err) => {
    console.log(err);
    ElMessage.error('获取用户列表失败');
  });
};

onMounted(() => {
  refreshTableData();
});

</script>

<style scoped>
.page_content {
  margin: 20px;
  padding: 20px;
  background-color: white;
}

.flex {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  /* margin-right: 5px; */
  padding: 10px;
}

.myButton {
  margin-right: 10px;
  height: 32px;
  line-height: 30px;
  background-color: #5ad2ad;
  border-color: #8ddc88;
  color: white;
  float:right;
}

.myButton1 {
  margin-right: 100px;
  height: 32px;
  line-height: 30px;
  background-color: #70a6e0;
  border-color: #80b4ec;
  color: white;
  float:right;
}
.input_box .el-input {
  width: 250px;
}

.el-button.link {
  color: #8ddc88;
  background-color: transparent;
  border-color: transparent;
}

.dialog-footer {
  text-align: right;
}

.message-box-content {
  display: flex;
  flex-direction: column;
}

.message-box-content p {
  margin: 0.5rem 0;
}
</style>